<?php
/**
 * 用户注册，对应接口为/common/user_register
 * User: devforma
 * Date: 14/12/12
 * Time: 15:43
 */

require LIB_DIR.'/phpass.class.php';

class UserRegister implements iController{
    /**
     * api请求处理
     * @param array $queryArgs 请求参数
     * @return array 返回结果
     */
    public function output($queryArgs) {
        global $uddb;
        
        //参数校验
        $validateUser = validateUser($queryArgs); //用户身份校验，注册用户不能使用该接口
        if ($validateUser == 1
            || !isset($queryArgs['mobile_num'])
            || !validatePhone($queryArgs['mobile_num'])
            || empty($queryArgs['password'])
            || (!empty($queryArgs['guest_id']) && $validateUser!=2)) {
            return genOutput(1000); //参数错误
        }

        $number = $queryArgs['mobile_num'];
        $password = $queryArgs['password'];
        
        //老用户使用邮箱登陆则使用user_email字段，手机号注册的用户使用phone字段
        $sql = "SELECT `ID` FROM `{$uddb->userAuthInfo}` WHERE `phone`=:phone";
        $uid = $uddb->getVar($sql, array(':phone'=>$number));

        //手机号已存在
        if (!empty($uid)) return genOutput(1102);

        //获取注册渠道来源
        $registerInfo = getRegisterInfo($queryArgs);

        $memKey = 'phone:'.$number;
        if (($value = cacheGet($memKey)) && $value['validated']) {
            //密码处理，采用wp的密码加密方式，保证邮箱和绑定的手机号的密码能共用
            //注意：登录时验证密码要使用phpass的CheckPassword函数来检验，不能直接加密后比对
            $passwordOrig = passDecrypt($password, ENCRYPTION_KEY);
            $phpass = new PasswordHash(8, true);
            $password = $phpass->HashPassword($passwordOrig);

            $result = $uddb->insert($uddb->userAuthInfo, [
                'user_pass'         => $password,
                'phone'             => $number,
                'register_source'   => $registerInfo['register_source'],
                'register_channel'  => $registerInfo['register_channel'],
                'register_activity' => $registerInfo['register_activity'],
                'campus_channel'    => $registerInfo['campus_channel'],
                'user_registered'   => date('Y-m-d H:i:s')
            ]);

            if (!$result) {
                return genOutput(1001);
            }

            $userId = $uddb->lastInsertId();
            
	        //生成登录token，并cache，便于其他api请求校验用户的有效性
            $userToken = md5($userId.':'.ENCRYPTION_KEY);
	        $uddb->update($uddb->userAuthInfo, array('user_token'=>$userToken), array('ID'=>$userId));

            $nickname = '*******'.substr($number, 7);
            $sno = self::genSno($userId);
            $uddb->insert($uddb->userSocialInfo, array('user_id' => $userId, 'nickname' => $nickname, 'user_sno' => $sno));
            cacheSet('user:'.$userId, array('token' => $userToken, 'guest_id' => 0));

            //清除该手机号的cache
            cacheDelete($memKey);

            if ($validateUser == 2) { //guest身份注册需要更新任务数据的
                $this->updateGuestData($queryArgs['guest_id'], $userId);
            }

            //成功
            return genOutput(1, array(
                'is_new' => true,
                'user' => array(
                    'user_id' => intval($userId),
                    'nickname' => $nickname,
                    'user_token' => $userToken,
                    'mobile_num' => $number,
                    'sno' => intval($sno),
                    'address' => '',
                    'avatar' => '',
                    'mail' => '',
                    'area' => '',
                    'birthday' => '',
                    'career' => '',
                    'weibo' => '',
                    'weixin' => '',
                    'enable_interview' => false,
                    'related_phone' => '',
                    'qq' => ''
                ),
                'exam_info' => new stdClass()
            ));
        }

        return genOutput(1103); //手机号未验证
    }

    /**
     * 游客数据关联
     * @param int $guestId 游客id
     * @param int $userId 用户id
     */
    private function updateGuestData($guestId, $userId) {
        global $uddb;
        
        $uddb->update($uddb->collection, array('user_id'=>$userId, 'guest_id'=>0),
            array('guest_id'=>$guestId));

        $uddb->update($uddb->historyMissionAction, array('user_id'=>$userId, 'guest_id'=>0),
            array('guest_id'=>$guestId));

        $uddb->update($uddb->userTests, array('user_id'=>$userId, 'guest_id'=>0),
            array('guest_id'=>$guestId));

        $uddb->update($uddb->recentAvMission, array('user_id'=>$userId, 'guest_id'=>0),
            array('guest_id'=>$guestId));

        $uddb->update($uddb->recentMissionInfo, array('user_id'=>$userId, 'guest_id'=>0),
            array('guest_id'=>$guestId));

        $uddb->update($uddb->userDPData, array('user_id'=>$userId, 'guest_id'=>0),
            array('guest_id'=>$guestId));
    }

    /**
     * 生成用户的学号
     * @param int $userId 用户id
     * @return string 学号
     */
    private static function genSno($userId) {
        return substr(strval(time()), -7).substr('00000'.$userId, -3);
    }
}
